package com.io.nettyflow.serverHandler;

import com.io.model.BaseModel;
import com.io.util.NettyUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Created by yangyx on 2016/7/21.
 */
@ChannelHandler.Sharable
public class VtsencoderHandler extends MessageToByteEncoder {

    static private VtsencoderHandler _sharedObj = null;

    static VtsencoderHandler sharedObj(){
        if(_sharedObj==null){
            _sharedObj = new VtsencoderHandler();
        }
        return _sharedObj;
    }
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if(o instanceof BaseModel){
            BaseModel model = (BaseModel)o;
            int beginIdx = byteBuf.writerIndex(); //是不是总是0？
            model.writeToByteBuff(byteBuf);
            int endIdx = byteBuf.writerIndex();
            short crcCal = NettyUtils.calculateCrc(byteBuf, beginIdx, endIdx);
            byteBuf.writeShort(crcCal);
        }
    }
}
